package cn.jbolt.ai.demo.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.jbolt.ai.core.embedding.EmbeddingService;
import cn.jbolt.ai.core.docParse.DocParseService;
import cn.jbolt.ai.demo.service.DemoService;
import cn.jbolt.ai.demo.vo.DimensionDemoVO;
import com.jboltai.resource.embedding.EmbeddingModelType;
import cn.jbolt.util.QiniuUtil;
import cn.jbolt.util.Result;
import com.jboltai.capability.text.JBoltText;
import com.jboltai.event.text.TextSplitEvent;
import com.jboltai.resource.embedding.EmbeddingModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service
public class DemoServiceImpl implements DemoService {

    private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);


    @Autowired
    private EmbeddingService embeddingService;
    @Autowired
    private DocParseService docParseService;


    private final QiniuUtil qiniuUtil;

    /**
     * 向量化演示
     *
     * @return
     */
    @Autowired
    public DemoServiceImpl(QiniuUtil qiniuUtil) {
        this.qiniuUtil = qiniuUtil;
    }

    @Override
    public Result embeddingDemo(DimensionDemoVO vo) {
        String text = vo.getText();
        String model = vo.getModel();
        if (StrUtil.isEmpty(model)) {
            return Result.error("请先选择资源,在进行向量化演示");
        }
        // 使用 indexOf() 找到第一个冒号的位置
        int index = model.indexOf(':');
        // 使用 substring() 方法来获取两个部分
        String modelType = model.substring(0, index);
        if (StrUtil.isEmpty(modelType)) {
            return Result.error("请先选择资源,在进行向量化演示");
        }
        EmbeddingModel embeddingModel = null;
        //判断是否是ollma
        if (modelType.equals(EmbeddingModelType.OLLAMA.getSn()) || modelType.equals(EmbeddingModelType.SILICONFLOW.getSn())) {
            embeddingModel = EmbeddingModel.getModel(modelType + "-" + model.substring(index + 1));
        } else {
            embeddingModel = EmbeddingModel.getModel(modelType);
        }

        if (embeddingModel == null) {
            return Result.error("请先选择资源,在进行向量化演示");
        }
        if (StrUtil.isBlankIfStr(text)) {
            return Result.error("请输入要向量化的文本");
        }
        return embeddingService.embeddingText(embeddingModel, text);
    }


    @Override
    public Result docParseDemo(String url) {
        return docParseService.docParse(url);
    }

    /**
     * 文档拆分
     *
     * @param url
     * @param chunkSize    分块大小
     * @param chunkOverlap 重叠大小
     * @return
     */
    @Override
    public Result docSplitDemo(String url, Integer chunkSize, Integer chunkOverlap) {
        if (chunkSize == null || chunkOverlap == 0) {
            return Result.error("请输入分块数量");
        }
        if (chunkOverlap == null || chunkOverlap == 0) {
            return Result.error("请输入重叠数量");
        }
        TextSplitEvent event = JBoltText.splitUrl(url, chunkSize, chunkOverlap).onFile((e, fileInfo) -> {
            try {
                String fileName = fileInfo.getFileName();
                Result<String> fileRes = qiniuUtil.uploadFile(fileInfo.getInputStream(), fileName, null);
                String path = fileRes.getData();
                logger.info("文档提取,图片上传成功, 图片地址: {}", path);
                return "![" + fileName + "](" + path + ")";
            } catch (Exception error) {
                logger.error("文档提取,图片上传失败, 图片文件名: {}, 失败原因: {}", fileInfo.getFileName(), error.getMessage());
                return null;
            }
        }).publish();
        event.await();
        if (event.isFail()) {
            return Result.error(event.getError().getFullMsg());
        }
        return Result.success(event.getResult().getChuncks());
    }


}
